﻿// MIT License Copyright 2014 (c) David Melendez. All rights reserved. See License.txt in the project root for license information.
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ElCamino.AspNet.Identity.AzureTable.Model;

namespace ElCamino.AspNet.Identity.AzureTable
{
    public class IdentityCloudContext : IdentityCloudContext<IdentityUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
        public IdentityCloudContext()
            : this(Constants.AppSettingsKeys.DefaultStorageConnectionStringKey) { }

        public IdentityCloudContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }
    }

    public class IdentityCloudContext<TUser> : IdentityCloudContext<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> where TUser : IdentityUser
    {
        public IdentityCloudContext()
            : this(Constants.AppSettingsKeys.DefaultStorageConnectionStringKey)
        {
        }

        public IdentityCloudContext(string connectionStringKey)
            : base(connectionStringKey)
        {
        }

    }

    public class IdentityCloudContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : TableServiceContext
        where TUser : IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim>
        where TRole : IdentityRole<TKey, TUserRole>
        where TUserLogin : IdentityUserLogin<TKey>
        where TUserRole : IdentityUserRole<TKey>
        where TUserClaim : IdentityUserClaim<TKey>
    {
        public IdentityCloudContext()
            : this(Constants.AppSettingsKeys.DefaultStorageConnectionStringKey) { }

        public IdentityCloudContext(string connectionStringKey)
            : base(CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting(connectionStringKey)).CreateCloudTableClient())
        {
            
        }

        public bool RequireUniqueEmail { get; set; }


        public CloudTable RoleTable
        {
            get
            {
                return this.ServiceClient.GetTableReference(Constants.TableNames.RolesTable);
            }
        }

        public CloudTable UserTable
        {
            get
            {
                return this.ServiceClient.GetTableReference(Constants.TableNames.UsersTable);
            }
        }

        internal CloudTable IndexTable
        {
            get
            {
                return this.ServiceClient.GetTableReference(Constants.TableNames.IndexTable);
            }
        }
    }

}
